﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Collections.Generic;

using TRPOP.CRM.Component.Business;
using TRPOP.CRM.Component.Common;
using TRPOP.CRM.Component.Model;
using TRPOP.Common;

namespace TRPOP.CRM.Web
{
    public partial class Employee_save : BaseAdmin
    {
        #region 权限限制
        protected override void SubPageInit()
        {
            base.m_oCurrentPermissionKey = "Employee_Employee";
        }
        #endregion

        #region 页面变量
        //记录传递参数EmployeeID
        public int m_intEmployeeID = 0;
        //注册用户
        public EmployeeInfo m_oEmployeeInfo = null;
        #endregion

        #region 页面事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindInfo();

                if (RequestHelper.RequestInt("id") > 0)
                {
                    m_intEmployeeID = RequestHelper.RequestInt("id");
                    BindEmployeeInfo();
                }
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            #region 信息验证

            if (txtEmployeeNum.Text.Trim().Length <= 0)
            {
                Alert("请输入员工编号");
                txtEmployeeNum.Focus();
                return;
            }

            if (txtEmployeeName.Text.Trim().Length <= 0)
            {
                Alert("请输入员工姓名");
                txtEmployeeNum.Focus();
                return;
            }

            if (txtStartTime.Text.Trim().Length <= 0)
            {
                Alert("请输入入职时间");
                txtStartTime.Focus();
                return;
            }

            if (txtMobile.Text.Trim().Length <= 0)
            {
                Alert("请输入手机号码");
                txtMobile.Focus();
                return;
            }
            #endregion

            //intEmployeeID大于0，则更新ID为intEmployeeID的Employee信息；否则插入Employee信息
            if (ViewState["EmployeeInfo"] != null)
            {
                m_oEmployeeInfo = ViewState["EmployeeInfo"] as EmployeeInfo;
            }
            else
            {
                m_oEmployeeInfo = new EmployeeInfo();

                //检测员工编号是否重复
                if (EmployeeManage.CheckEmployeeNumberExist(txtEmployeeNum.Text.Trim()))
                {
                    Alert("员工编号重复，请输入员工编号");
                    txtEmployeeNum.Focus();
                    return;
                }

                //检测员工登录名是否重复
                if (EmployeeManage.CheckEmployeeNameExist(txtEmployeeName.Text.Trim()))
                {
                    Alert("员工姓名不能重复，请输入员工姓名");
                    txtEmployeeName.Focus();
                    return;
                }

                m_oEmployeeInfo.dtCreationTime = DateTime.Now;
                m_oEmployeeInfo.dtEndDate = DateTime.Now;
                m_oEmployeeInfo.dtLastLoginTime = DateTime.Now;
                m_oEmployeeInfo.nvcLoginPassword = "123456".MD5Normal();
            }

            //员工基本资料
            m_oEmployeeInfo.iEmployeeStatusID = ddlEmployeeStatus.SelectedValue.ToInt();
            m_oEmployeeInfo.nvcEmployeeNumber = txtEmployeeNum.Text.Trim().HtmlEncode();
            m_oEmployeeInfo.nvcEmployeeName = txtEmployeeName.Text.Trim();

            m_oEmployeeInfo.bEnableLogin = true;

            m_oEmployeeInfo.bGender = rbtnlstGender.SelectedValue.ToBool();
            m_oEmployeeInfo.dtBirthday = txtBirthday.Text.Trim().ToDateTime();

            //所过生日类型 
            m_oEmployeeInfo.bIsSolarBitthday = rbtnIsSolarBirthday.SelectedValue.ToBool();

            m_oEmployeeInfo.dtStartDate = txtStartTime.Text.Trim().ToDateTime();
            m_oEmployeeInfo.iDepartmentID = ddlDepartment.SelectedValue.ToInt();
            m_oEmployeeInfo.iJobTitleID = ddlJobTitle.SelectedValue.ToInt();

            //员工头像信息上传
            if (fuEmployeeImage.HasFile)
            {
                int intFileLength = 0;

                HttpPostedFile hpImageup = fuEmployeeImage.PostedFile;
                intFileLength = hpImageup.ContentLength;

                //文件大小判断
                if (intFileLength > 2 * 1024 * 1024 || intFileLength <= 0)
                {
                    Alert("上传图片大小不正确");
                    return;
                }
                else
                {
                    ////文件类型判断
                    string strFileExtention = hpImageup.FileName.Substring(hpImageup.FileName.LastIndexOf(".") + 1).ToLower();

                    string[] strValidExtention = { "jpg", "jpeg", "png", "gif" };

                    if (!strValidExtention.Contains(strFileExtention))
                    {
                        Alert("上传图片格式不正确");
                        return;
                    }

                    //文件临时存储为byte数组
                    byte[] bytFileInfo = new byte[intFileLength];
                    //建立数据流
                    Stream streamObject = hpImageup.InputStream;
                    //读取文件数据，bytFileInfo为数据储存体，0为数据指针位置，intFileLength为数据长度
                    streamObject.Read(bytFileInfo, 0, intFileLength);

                    m_oEmployeeInfo.nvcImageBinaryExtension = strFileExtention;

                    m_oEmployeeInfo.bnImageBinary = bytFileInfo;
                    m_oEmployeeInfo.ntExtendedProperity = hpImageup.ContentType;

                    //关闭数据流
                    streamObject.Close();
                }
            }

            //员工联系方式
            m_oEmployeeInfo.nvcMobile = txtMobile.Text.Trim().HtmlEncode();
            m_oEmployeeInfo.nvcEmail = txtEmail.Text.Trim().HtmlEncode();
            m_oEmployeeInfo.nvcPostalCode = txtPostalCode.Text.Trim().HtmlEncode();
            m_oEmployeeInfo.nvcCountry = ddlCountry.SelectedValue.Trim().HtmlEncode();
            m_oEmployeeInfo.nvcProvince = RequestHelper.RequestString("txtProvince");//DDLProvince.Value.Trim().HtmlEncode();
            m_oEmployeeInfo.nvcCity = RequestHelper.RequestString("txtCity"); //DDLCity.Value.Trim().HtmlEncode();
            m_oEmployeeInfo.nvcStreet1 = txtStreet.Text.Trim().HtmlEncode();
            m_oEmployeeInfo.nvcStreet2 = txtStreet1.Text.Trim().HtmlEncode();

            //员工紧急联系人
            m_oEmployeeInfo.nvcEmergencyContactName = txtEmergencyContactName.Text.Trim().HtmlEncode();
            m_oEmployeeInfo.nvcEmergencyContactPhone1 = txtEmergencyContactPhone1.Text.Trim().HtmlEncode();
            m_oEmployeeInfo.nvcEmergencyContactPhone2 = txtEmergencyContactPhone2.Text.Trim().HtmlEncode();

            //出生日期
            m_oEmployeeInfo.dtBirthday = txtBirthday.Text.Trim().ToDateTime();

            m_oEmployeeInfo.dtLastModified = DateTime.Now;

            if (txtPwd.Text.IsEmpty() == false)
            {
                m_oEmployeeInfo.nvcLoginPassword = txtPwd.Text.Trim().MD5Normal();
            }
           

            bool bResult = EmployeeManage.SaveEmployeeInfo(m_oEmployeeInfo);

            if (bResult)
            {
                if (ddlSystemRole.Items.Count > 0 && ddlSystemRole.SelectedIndex >= 0)
                {
                    if (PermissionManage.SaveEmployeeRoleInfo(m_oEmployeeInfo.iEmployeeID, ddlSystemRole.SelectedValue.ToInt()))
                    {

                    }
                }
                
                Alert("员工信息保存成功", "Employee_list.aspx");
            }
            else
            {
                Alert("员工信息保存失败");
            }
        }
        #endregion

        #region 页面方法
        /// <summary>
        /// 绑定基本的信息
        /// </summary>
        private void BindInfo()
        {
            //绑定所有员工状态信息
            PageBindHelper.BindEmployeeStatusInfo(ddlEmployeeStatus);

            //绑定所有职位信息
            PageBindHelper.BindJobTitleInfo(ddlJobTitle);

            //绑定所有部门信息
            PageBindHelper.BindDepartmentInfo(ddlDepartment, 0);

            //绑定所有的系统角色
            PageBindHelper.BindSystemRole(ddlSystemRole);
        }

        /// <summary>
        /// 绑定员工信息
        /// </summary>
        private void BindEmployeeInfo()
        {
            m_oEmployeeInfo = EmployeeManage.GetEmployeeInfo(m_intEmployeeID);

            if (m_oEmployeeInfo != null)
            {
                ViewState["EmployeeInfo"] = m_oEmployeeInfo;

                //员工基本信息
                ddlEmployeeStatus.SelectedValue = m_oEmployeeInfo.iEmployeeStatusID.ToString();
                ddlEmployeeStatus.Enabled = false;

                txtEmployeeNum.Text = m_oEmployeeInfo.nvcEmployeeNumber.Trim();
                txtEmployeeNum.Enabled = false;

                txtEmployeeName.Text = m_oEmployeeInfo.nvcEmployeeName.Trim();
                txtEmployeeName.Enabled = false;

                rbtnlstGender.SelectedValue = m_oEmployeeInfo.bGender ? "1" : "0";
                rbtnIsSolarBirthday.SelectedValue = m_oEmployeeInfo.bIsSolarBitthday ? "1" : "0";

                txtBirthday.Text = m_oEmployeeInfo.dtBirthday.ToString("yyyy-MM-dd");
                txtStartTime.Text = m_oEmployeeInfo.dtStartDate.ToString("yyyy-MM-dd");

                ddlDepartment.SelectedValue = m_oEmployeeInfo.iDepartmentID.ToString();
                ddlJobTitle.SelectedValue = m_oEmployeeInfo.iJobTitleID.ToString();

                //员工联系方式
                txtMobile.Text = m_oEmployeeInfo.nvcMobile.Trim();
                txtEmail.Text = m_oEmployeeInfo.nvcEmail.Trim();
                txtPostalCode.Text = m_oEmployeeInfo.nvcPostalCode.Trim();
                txtCountry.Text = m_oEmployeeInfo.nvcCountry.Trim();
                txtProvince.Value = m_oEmployeeInfo.nvcProvince.Trim();
                txtCity.Value = m_oEmployeeInfo.nvcCity.Trim();
                txtStreet.Text = m_oEmployeeInfo.nvcStreet1.Trim();
                txtStreet1.Text = m_oEmployeeInfo.nvcStreet2.Trim();

                //员工紧急联系人
                txtEmergencyContactName.Text = m_oEmployeeInfo.nvcEmergencyContactName.Trim();
                txtEmergencyContactPhone1.Text = m_oEmployeeInfo.nvcEmergencyContactPhone1.Trim();
                txtEmergencyContactPhone2.Text = m_oEmployeeInfo.nvcEmergencyContactPhone2.Trim();

                //绑定员工头像
                if (m_oEmployeeInfo.bnImageBinary != null)
                {
                    if (m_oEmployeeInfo.bnImageBinary.Length > 0)
                    {
                        dvImg.InnerHtml = string.Format("<img alt='{0}' title='{0}' src='/Employee/Employee_photo.aspx?EmployeeID={1}' width='125px' height='125px' />", m_oEmployeeInfo.nvcEmployeeName, m_oEmployeeInfo.iEmployeeID);
                    }
                }

                EmployeeRoleInfo oEmployeeRoleInfo = PermissionManage.GetEmployeeRoleInfo(m_oEmployeeInfo.iEmployeeID);
                if (oEmployeeRoleInfo != null)
                {
                    ddlSystemRole.SelectedValue = oEmployeeRoleInfo.iSystemRoleID.ToString();
                }

            }
        }
        #endregion
    }
}